#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
智能语音控制系统状态检查脚本
"""

import requests
import subprocess
import sys

def check_backend():
    """检查后端服务"""
    try:
        response = requests.get("http://localhost:18080/check", timeout=5)
        if response.status_code == 200:
            data = response.json()
            if data.get("code") == 0:
                print("✅ 后端服务正常运行 (http://localhost:18080)")
                return True
        print("❌ 后端服务响应异常")
        return False
    except requests.exceptions.RequestException:
        print("❌ 后端服务连接失败 (http://localhost:18080)")
        return False

def check_frontend():
    """检查前端服务"""
    try:
        response = requests.get("http://localhost:3001", timeout=5)
        if response.status_code == 200:
            # 检查是否包含Vue应用的特征
            if "智能语音控制系统" in response.text or "<!DOCTYPE html>" in response.text:
                print("✅ 前端服务正常运行 (http://localhost:3001)")
                return True
        print(f"❌ 前端服务响应异常 (状态码: {response.status_code})")
        return False
    except requests.exceptions.RequestException as e:
        print(f"❌ 前端服务连接失败 (http://localhost:3001): {e}")
        return False

def check_processes():
    """检查相关进程"""
    try:
        # 检查Python进程
        result = subprocess.run(['pgrep', '-f', 'app.py'], capture_output=True, text=True)
        if result.returncode == 0:
            print("✅ 后端进程运行中")
        else:
            print("❌ 后端进程未找到")
        
        # 检查Node进程
        result = subprocess.run(['pgrep', '-f', 'npm run dev'], capture_output=True, text=True)
        if result.returncode == 0:
            print("✅ 前端进程运行中")
        else:
            print("❌ 前端进程未找到")
            
    except Exception as e:
        print(f"⚠️ 进程检查失败: {e}")

def main():
    """主函数"""
    print("🔍 智能语音控制系统状态检查")
    print("=" * 40)
    
    backend_ok = check_backend()
    frontend_ok = check_frontend()
    
    print("\n📊 进程状态:")
    check_processes()
    
    print("\n" + "=" * 40)
    if backend_ok and frontend_ok:
        print("🎉 系统运行正常！")
        print("\n🌐 访问地址:")
        print("   前端界面: http://localhost:3001")
        print("   后端API: http://localhost:18080")
        return 0
    else:
        print("⚠️ 系统存在问题，请检查服务状态")
        print("\n🔧 解决方案:")
        if not backend_ok:
            print("   1. 检查后端服务: python app.py")
        if not frontend_ok:
            print("   2. 检查前端服务: cd font && npm run dev")
        return 1

if __name__ == "__main__":
    sys.exit(main())
